<?php

/*
* Front end plugin extension to manage application initialization
*/
require_once('Zend/Controller/Plugin/Abstract.php');

require_once('Myzen/log/Executiontime.php');

/**
 * Plugin to save the execution time of each query
 * 
 * @uses Zend_Controller_Plugin_Abstract
 */
class Myzen_Controller_Plugin_Asynchronous extends Zend_Controller_Plugin_Abstract
{
	protected $_alreadyCalled = false;
   
    protected $_config = null; 
  /**
   * Constructor
   *
   * @param  config
   * @return void
  **/
	public function __construct()
	{
		$this->_config = Zend_Registry::get('dt_config');
		return;
	}

	public function routeShutdown(Zend_Controller_Request_Abstract $request) 
	{
		//avoid infinite loop
        if('asynchronous' == $request->getParam('module')) $this->_alreadyCalled = true;
        
        //Set the asynchronous queue
		$queue = new Zend_Queue('ShardDb', $this->_config->asynchronous->queue);
		//save the queue in the registry
		Zend_Registry::set('dt_asynchronousQueue',$queue);
    }
	
	public function dispatchLoopShutdown()
    {

		//if we are in a cron job we publish the message to the cron database
		//$cronJobId = $this->getRequest()->_getParam('draftrack_cronjobId');
		$cronJobId = $this->getRequest()->getParam('draftrack_cronjobId');
		if(!empty($cronJobId)) {
			$message = $this->getResponse()->getBody();
			require_once('asynchronous/objects/cronjobRun.php');
			$cronJobRun = new asynchronous_Object_CronjobRun($cronJobId);
			$cronJobRun->setOutputMessage($message);
		}

		if($this->_alreadyCalled) return;

		//if the asynchronous should be processed inline, we call it

		if($this->_config->asynchronous->mode == 'inline') $this->_callAsynchronous();
		$this->_alreadyCalled = true;
		

		
    }

	
	
	
	protected function _callAsynchronous() {

	 	$baseURL = Zend_Controller_Front::getInstance()->getBaseUrl();
		$websiteURL = $this->_config->website_url;
		// Windows
		if(self::_isWindows()){
			$command = 'start /b curl '.$websiteURL.$baseURL.'/asynchronous/message/process/';
			pclose(popen($command, 'r'));
			Zend_Registry::get('dt_log')->log('calling asynchronous windows:'.$command,6);
		}
	 
		// Some sort of UNIX
		else {
			$command = 'curl '.$websiteURL.$baseURL.'/asynchronous/message/process/ /dev/null &';
			pclose(popen($command, 'r'));
			Zend_Registry::get('dt_log')->log('calling asynchronous unix:'.$command,6);
		}
		return true;
	}
 
 
	/**
	* Is Windows
	*
	* Tells if we are running on Windows Platform
	* @author raccettura
	*/
	static protected function _isWindows(){
		if(PHP_OS == 'WINNT' || PHP_OS == 'WIN32'){
			return true;
		}
		return false;
	}	

 

} // end plugin AsynchronousCall